import 'package:flutter/material.dart';
import 'package:custom_refresh_indicator/custom_refresh_indicator.dart';

import 'package:flutter_study/widgets/public/themes/index.dart';
import 'package:flutter_study/widgets/public/app_empty.dart';

class AppListView extends StatefulWidget {
  const AppListView(
      {super.key,
      this.isLast = false,
      this.onLoad,
      this.onRefresh,
      this.itemCount,
      this.itemExtent,
      this.padding,
      required this.itemBuilder});
  final bool isLast;
  final Future<void> Function()? onLoad;
  final Future<void> Function()? onRefresh;

  final int? itemCount;
  final double? itemExtent;
  final EdgeInsetsGeometry? padding;
  final Widget? Function(BuildContext, int) itemBuilder;

  @override
  AppListViewState createState() => AppListViewState();
}

class AppListViewState extends State<AppListView> {
  late final IndicatorController controller;

  IndicatorTrigger get trigger {
    if (widget.onLoad == null || isEmpty || widget.isLast) {
      return IndicatorTrigger.leadingEdge;
    }

    return IndicatorTrigger.bothEdges;
  }

  bool get isEmpty => widget.itemCount == null || widget.itemCount == 0;
  @override
  void initState() {
    super.initState();
    controller = IndicatorController();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    late final Widget child;
    if (isEmpty) {
      child = const AppListEmpty();
    } else {
      child = ListView.builder(
        padding: widget.padding,
        itemCount: widget.itemCount,
        itemExtent: widget.itemExtent,
        itemBuilder: widget.itemBuilder,
      );
    }

    return CustomMaterialIndicator(
        child: child,
        onRefresh: () async {
          if (controller.edge == IndicatorEdge.leading) {
            await widget.onRefresh?.call();
          }
          if (controller.edge == IndicatorEdge.trailing) {
            await widget.onLoad?.call();
          }
        },
        trigger: trigger,
        controller: controller,
        indicatorBuilder: (context, controller) {
          return Icon(
            Icons.refresh,
            size: 30,
            color: AppThemes.of().colors.spinkit,
          );
        });
  }
}
